package se_dsp_adv_creative

import (
	"context"
	"errors"
	"fmt"
	"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss"
	"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss/credentials"
	"github.com/gabriel-vasile/mimetype"
	"github.com/gin-gonic/gin"
	"io"
	"net/http"
	"os"
	"path/filepath"
	"time"
)

func UploadFileVideoOss(c *gin.Context) {
	// 限制上传大小
	errr := c.Request.ParseMultipartForm(50 << 20) // 50MB
	if errr != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": -1,
			"msg":  "file limit 10M :" + errr.Error(),
			"data": nil,
		})
		return
	}

	file, header, err := c.Request.FormFile("file")
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": -1,
			"msg":  "file upload error1:" + err.Error(),
			"data": nil,
		})
		return
	}

	defer file.Close()
	//上传文件
	uploadDir := "./upload_crt"
	// 生成唯一文件名
	oldname := header.Filename
	ext := filepath.Ext(header.Filename)
	newFilename := fmt.Sprintf("%d%s", time.Now().UnixNano(), ext)
	filePath := filepath.Join(uploadDir, newFilename)
	// 保存文件
	out, err := os.Create(filePath)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": -1,
			"msg":  "file upload error3:" + err.Error(),
			"data": nil,
		})
		return
	}
	defer out.Close()

	_, err = io.Copy(out, file)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": -1,
			"msg":  "file upload error4:" + err.Error(),
			"data": nil,
		})
		return
	}

	mtype, err := mimetype.DetectFile(filePath)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": -1,
			"msg":  "file upload error5:" + err.Error(),
			"data": nil,
		})
		return
	}
	if !mtype.Is("video/mp4") {
		c.JSON(http.StatusOK, gin.H{
			"code": -1,
			"msg":  "file upload type error",
			"data": nil,
		})
		return
	}

	fileInfo, _ := os.Stat(filePath)
	sizeKB := float64(fileInfo.Size()) / 1024

	//上传至阿里云oss
	objname := "video/" + newFilename
	isok, err := UploadFileAliOss(filePath, objname)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": -1,
			"msg":  "file upload type error:" + err.Error(),
			"data": nil,
		})
		return
	}
	if isok {
		os.Remove(filePath)
	}
	c.JSON(http.StatusOK, gin.H{
		"code": 0,
		"msg":  "success",
		"data": map[string]interface{}{
			"adm_type": "2",
			"ad_name":  oldname,
			"ad_file":  newFilename,
			"desc":     "",
			"width":    0,
			"height":   0,
			"duration": 0,
			"size":     sizeKB,
			"cimg":     "",
			"ad_urls":  "http://hxsu.huayanz.com/" + objname,
		},
	})
	return
}

func UploadFileImgOss(c *gin.Context) {
	// 限制上传大小
	errr := c.Request.ParseMultipartForm(20 << 20) // 20MB
	if errr != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": -1,
			"msg":  "file limit 10M :" + errr.Error(),
			"data": nil,
		})
		return
	}

	file, header, err := c.Request.FormFile("file")
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": -1,
			"msg":  "file upload error1:" + err.Error(),
			"data": nil,
		})
		return
	}
	defer file.Close()
	//上传文件
	uploadDir := "./upload_crt"
	// 生成唯一文件名
	oldname := header.Filename
	ext := filepath.Ext(header.Filename)
	newFilename := fmt.Sprintf("%d%s", time.Now().UnixNano(), ext)
	filePath := filepath.Join(uploadDir, newFilename)
	// 保存文件
	out, err := os.Create(filePath)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": -1,
			"msg":  "file upload error3:" + err.Error(),
			"data": nil,
		})
		return
	}
	defer out.Close()

	_, err = io.Copy(out, file)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": -1,
			"msg":  "file upload error4:" + err.Error(),
			"data": nil,
		})
		return
	}

	mtype, err := mimetype.DetectFile(filePath)
	if err != nil && err != io.EOF {
		c.JSON(http.StatusOK, gin.H{
			"code": -1,
			"msg":  "file upload error2 :" + errr.Error(),
			"data": nil,
		})
		return
	}
	if !mtype.Is("image/webp") && !mtype.Is("image/jpeg") && !mtype.Is("image/png") && !mtype.Is("image/jpg") {
		c.JSON(http.StatusOK, gin.H{
			"code": -1,
			"msg":  "file upload type error",
			"data": nil,
		})
		return
	}

	fileInfo, _ := os.Stat(filePath)
	sizeKB := float64(fileInfo.Size()) / 1024

	//上传至阿里云oss
	objname := "image/" + newFilename
	isok, err := UploadFileAliOss(filePath, objname)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": -1,
			"msg":  "file upload type error:" + err.Error(),
			"data": nil,
		})
		return
	}
	if isok {
		os.Remove(filePath)
	}
	c.JSON(http.StatusOK, gin.H{
		"code": 0,
		"msg":  "success",
		"data": map[string]interface{}{
			"adm_type": "1",
			"ad_name":  oldname,
			"ad_file":  newFilename,
			"desc":     "",
			"width":    0,
			"height":   0,
			"duration": 0,
			"size":     sizeKB,
			"cimg":     "",
			"ad_urls":  "http://hxsu.huayanz.com/" + objname,
		},
	})
	return
}

func UploadFileAliOss(localFile, objectName string) (bool, error) {
	// 加载默认配置并设置凭证提供者和区域
	// 设置静态凭据
	staticCredentials := credentials.NewStaticCredentialsProvider("LTAI5tD8HUExttKsQnEP2Qne", "hukacWCMSNBZ2ylXBCxB3ysyhhipIE")

	cfg := oss.LoadDefaultConfig().
		WithCredentialsProvider(staticCredentials).
		WithRegion("cn-beijing")
	// 创建OSS客户端
	client := oss.NewClient(cfg)
	// 创建上传对象的请求
	putRequest := &oss.PutObjectRequest{
		Bucket:       oss.Ptr("morandsp"),      // 存储空间名称
		Key:          oss.Ptr(objectName),      // 对象名称
		StorageClass: oss.StorageClassStandard, // 指定对象的存储类型为标准存储
		//Acl:          oss.ObjectACLPublicRead,  // 指定对象的访问权限为私有访问
		//Metadata: map[string]string{
		//	"yourMetadataKey1": "yourMetadataValue1", // 设置对象的元数据
		//},
	}
	// 执行上传对象的请求
	result, err := client.PutObjectFromFile(context.TODO(), putRequest, localFile)
	if err != nil {
		return false, err
	}
	if result.StatusCode == 200 {
		return true, nil
	}
	return false, errors.New("UploadFileAliOss=" + result.Status)
}
